package com.hengpeng.msls.expresslogin.alipay;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.hengpeng.itfinbase.persist.MemberShare.UserType;
import com.hengpeng.msls.constants.LSConstants;
import com.hengpeng.msls.expresslogin.ExpressNotifyService;
import com.hengpeng.msls.expresslogin.alipay.util.AlipayNotify;
import com.hengpeng.msls.expresslogin.alipay.util.EncodeUtil;
import com.hengpeng.msls.expresslogin.dto.LoginResultDto;

public class AlipayNotifyImpl implements ExpressNotifyService
{
	public LoginResultDto validataNotify(HttpServletRequest request, UserType userType)
	{
		LoginResultDto dto = new LoginResultDto(false, UserType.ALIPAY);
		Map<String, String> configLogin = new HashMap<String, String>();
//		configLogin.put(AlipayConfig.partner, StoreConfigUtil.getStoreParameter(request, AlipayConfig.partner));
//		configLogin.put(AlipayConfig.key, StoreConfigUtil.getStoreParameter(request, AlipayConfig.key));

		// 获取支付宝GET过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();)
		{
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++)
			{
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			try
			{
				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			}
			catch (UnsupportedEncodingException e)
			{
				e.printStackTrace();
			}
			params.put(name, valueStr);
		}

		// 计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params, configLogin);
		if (verify_result)
		{
			dto.setIsSuccess(verify_result);
			String user_id = EncodeUtil.convertToUTF8(request.getParameter("user_id"));
			String email = EncodeUtil.convertToUTF8(request.getParameter("email"));
			String realName = EncodeUtil.convertToUTF8(request.getParameter("real_name"));
			dto.setUserId(user_id);
			dto.setEmail(email);
			dto.setRealName(realName);
		}

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// // 支付宝用户id
		// String user_id = request.getParameter("user_id");
		// // 授权令牌，在支付宝充值时用到
		String token = request.getParameter("token");
		request.getSession().setAttribute(LSConstants.CLIENT_SESSION_ALIPAY_TOKEN, token);
		// System.out.println("user_id:" + user_id);
		// System.out.println("token:" + token);
		// System.out.println("eamil" + request.getParameter("email"));
		// System.out.println("real_name" + request.getParameter("real name"));
		// System.out.println(request.getParameter("is success"));
		return dto;
	}
}
